package com.adam.example.search;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.json.JsonData;
import com.adam.example.ElasticsearchClientHolder;
import com.adam.example.types.PercolateLaptop;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class SearchPercolateExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient client = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();

        PercolateLaptop laptop = new PercolateLaptop(9999, "macbook pro");
        SearchRequest searchRequest = SearchRequest.of(builder -> builder
                        .index("test_percolate")
                        .query(queryBuilder -> queryBuilder
                                .percolate(percolateQueryBuilder -> percolateQueryBuilder
                                        .field("query")
                                        .document(JsonData.of(laptop))
                                )
                )
        );

        SearchResponse<Map> searchResponse = client.search(searchRequest, Map.class);
        HitsMetadata<Map> hitsMetadata = searchResponse.hits();
        System.out.println("搜索到" + hitsMetadata.total().value() + "条数据");
        List<Hit<Map>> queryHitList = hitsMetadata.hits();
        for(int i=0;i<queryHitList.size();i++) {
            Hit<Map> queryHit = queryHitList.get(i);
            Map<String, Object> query = (Map<String, Object>) queryHit.source();
            System.out.println("文档[" + (i+1) + "][评分" + queryHit.score() + "]:" + query);
        }

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
